package com.example.demo.service.impl;

import com.example.demo.common.Result;
import com.example.demo.dto.BuyTicketDTO;
import com.example.demo.dto.SearchTicketGetDTO;
import com.example.demo.entity.OrderTable;
import com.example.demo.entity.User;
import com.example.demo.mapper.BuyTicketMapper;
import com.example.demo.mapper.CheciMapper;
import com.example.demo.service.BuyTicketService;
import com.example.demo.util.JWTUtil;
import com.example.demo.vo.ResponseData;
import com.example.demo.vo.TicketInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class BuyTicketServiceImpl implements BuyTicketService {
    @Autowired
    private BuyTicketMapper buyTicketMapper;

    @Autowired
    private CheciMapper checiMapper;

    @Override
    public Result buyTicket(BuyTicketDTO buyTicketDTO, String token) {
        // 获取用户id
        token = token.substring(7);
        Integer userId = JWTUtil.parseToken(token).getId(); //令牌中含有id和name

        OrderTable orderTable = new OrderTable();
        orderTable.setUserId(userId);
        orderTable.setBoardingTime(buyTicketDTO.getBoardingTime());
        orderTable.setDropOffTime(buyTicketDTO.getDropOffTime());
        orderTable.setCheciId(buyTicketDTO.getCheciId());
        orderTable.setStartPlace(buyTicketDTO.getStartPlace());
        orderTable.setEndPlace(buyTicketDTO.getEndPlace());
        orderTable.setPrice(buyTicketDTO.getPrice());
        LocalDateTime localDateTime =LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        orderTable.setCreateTime(dtf.format(localDateTime));
        // 添加到订单表
        int res = buyTicketMapper.insertOrder(orderTable);
        if( res == 0 ) return Result.fail();
        // 剩余票数减一
        int cnt = checiMapper.updateLastSeats(buyTicketDTO.getCheciId());
        if( cnt == 0 ) return Result.fail();
        return Result.success();
    }

    @Override
    public Result getTicketInfo(SearchTicketGetDTO getDTO) {
        if(getDTO.getStartPlace() == null || getDTO.getEndPlace() == null){
            return Result.success();
        }
        List<TicketInfoVO> data = new ArrayList<>();

        // 第一步查询获取车次，车辆，车型，剩余座位
        Map<Integer, Map> data1 = buyTicketMapper.firstSelect(getDTO);
        System.out.println(data1);

        // 第二步查询上下车时的停站时间，价格
        for(Map.Entry<Integer, Map> entry : data1.entrySet()) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
            Integer checiId = entry.getKey();
            Map mp1 = buyTicketMapper.secondSelect(checiId, getDTO.getStartPlace());
            Map mp2 = buyTicketMapper.secondSelect(checiId, getDTO.getEndPlace());

            //第三步计算价格
            TicketInfoVO ticketInfoVO = new TicketInfoVO();
            String type = entry.getValue().get("type").toString();
            String vehicleId = entry.getValue().get("vehicleId").toString();
            Integer lastSeats = (Integer) entry.getValue().get("lastSeats");
            ticketInfoVO.setCheciId(checiId);
            ticketInfoVO.setType(type);
            ticketInfoVO.setVehicleId(vehicleId);
            ticketInfoVO.setSeats(lastSeats);
            ticketInfoVO.setDropOffTime(mp2.get("stopTime").toString());
            Double price = 0.0;
            if(mp1 == null){
                ticketInfoVO.setBoardingTime(entry.getValue().get("startTime").toString());
                price = (Double) mp2.get("price");
            }else{
                ticketInfoVO.setBoardingTime(mp1.get("stopTime").toString());
                price = (Double) mp2.get("price") - (Double) mp1.get("price");
            }

            ticketInfoVO.setPrice(price);
            data.add(ticketInfoVO);
        }
        ResponseData responseData = new ResponseData();
        responseData.setTotal(data1.size());
        responseData.setList(data);
        return Result.success(responseData);
    }
}
